#!/bin/bash

# Docker环境下修复parent_recurring_id外键约束问题
echo "🔍 Docker环境修复parent_recurring_id外键约束问题..."

# 查找后端容器名
BACKEND_CONTAINER=$(docker ps --filter "name=backend" --format "{{.Names}}" | head -n 1)

if [ -z "$BACKEND_CONTAINER" ]; then
    echo "❌ 未找到后端容器，请检查容器是否运行"
    echo "💡 尝试查找所有运行的容器:"
    docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}"
    exit 1
fi

echo "✅ 找到后端容器: $BACKEND_CONTAINER"

# 在后端容器中运行修复脚本
echo "🔧 在容器中执行修复..."
docker exec -i $BACKEND_CONTAINER node -e "
const { Pool } = require('pg');

const pool = new Pool({
  host: process.env.DB_HOST || 'postgres',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'aide',
  user: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD
});

async function fix() {
  try {
    console.log('🔍 检查外键约束问题...');
    
    // 检查问题记录
    const badRecords = await pool.query(\`
      SELECT COUNT(*) as count
      FROM tasks t1
      LEFT JOIN tasks t2 ON t1.parent_recurring_id = t2.id
      WHERE t1.parent_recurring_id IS NOT NULL AND t2.id IS NULL
    \`);
    
    console.log(\`📊 发现 \${badRecords.rows[0].count} 条有问题的记录\`);
    
    if (badRecords.rows[0].count > 0) {
      // 执行修复
      const result = await pool.query(\`
        UPDATE tasks 
        SET parent_recurring_id = NULL
        WHERE parent_recurring_id IS NOT NULL 
          AND parent_recurring_id NOT IN (SELECT id FROM tasks)
      \`);
      
      console.log(\`✅ 修复完成! 更新了 \${result.rowCount} 条记录\`);
    } else {
      console.log('✅ 没有发现问题');
    }
    
    // 显示统计
    const stats = await pool.query(\`
      SELECT 
        COUNT(*) as total_tasks,
        COUNT(CASE WHEN is_recurring = true THEN 1 END) as recurring_tasks,
        COUNT(CASE WHEN parent_recurring_id IS NOT NULL THEN 1 END) as tasks_with_parent
      FROM tasks
    \`);
    
    const s = stats.rows[0];
    console.log('📊 统计信息:');
    console.log(\`   总任务: \${s.total_tasks}, 重复任务: \${s.recurring_tasks}, 有父任务: \${s.tasks_with_parent}\`);
    
  } catch (error) {
    console.error('❌ 错误:', error.message);
  } finally {
    await pool.end();
  }
}

fix();
"

echo "🎉 修复完成!"
